processSupportRequest
| Admin Notification | User Confirmation |
|---|---|
![]() | ![]() |
- ๐ฌ๐ง English
- ๐ฎ๐น Italian
Function Name: processSupportRequest
Author: Domenico Cerone Creation Date: 25/09/2025
Last Reviewer: Domenico Cerone
Trigger: HTTPS (onRequest)
Purpose: Manages the processing and sending of email notifications for user support requests through a dual notification system. When a support request is received, it automatically sends a notification to administrators with all details and attachments, and a confirmation email to the user who created the request.
Detailed Functionalityโ
This module handles the complete processing of support requests through a dual notification system:
1. TRIGGER AND INPUTโ
- Receives HTTP POST requests with 'supportRequestId' parameter
- Example:
{ "supportRequestId": "tMulEHxpGe4q0Sc9zmaf" } - Input validation and HTTP method checking
2. SUPPORT REQUEST DATA RETRIEVALโ
- Accesses Firestore 'SupportRequests' collection
- Retrieves document using the provided ID parameter
- Extracts: email, supportType, title, description, createdAt, images[]
- Error handling if document doesn't exist
3. ADMINISTRATOR IDENTIFICATIONโ
- Query on 'Profiles' collection with filter:
role == 'Admin' - Collects array of administrator recipient emails
- Fallback error if no admin found in the system
4. REQUESTING USER PROFILE RETRIEVALโ
- Uses email from support request as document ID in 'Profiles'
- Extracts firstName and lastName for full name
- Fallback logic: if name not available, uses email
- Result: "Michele Telesca" or "92mt@live.it"
5. NOTIFICATION PREFERENCE CHECKโ
- Checks if the user has enabled the processSupportRequest notification in their notification preferences
- Verifies
notification_types.processSupportRequestfield in the profile - If notification is disabled (false): returns success without sending email
- If notification is enabled (true): proceeds with administrator identification
- Provides clear logging about notification preference status
6. ATTACHMENT DOWNLOAD AND PREPARATIONโ
- Iterates 'images' array from support request
- For each image: download from Firebase Storage URL
- Conversion to base64 format for email attachment
- Automatic MIME type detection from file extension
- 30-second timeout to avoid network blocks
- Error handling for failed downloads
7. DUAL EMAIL SYSTEMโ
A) ADMINISTRATOR EMAILโ
- Template:
13ef.8598f19fbcc5adb.k1.d36f1920-618a-11f0-ae4f-dad70ff08860.1980e8f5bb2 - Recipients: ALL users with role='Admin'
- Attachments: All support request images
- Merge data:
- profile: user full name ("Michele Telesca")
- createdAt: Italian formatted date ("15/07/2025, 14:51:22")
- supportType: request type ("bug_report")
- title: request title ("Bug assurdo nella frame!")
- description: complete problem description
B) USER CONFIRMATION EMAILโ
- Template:
13ef.8598f19fbcc5adb.k1.94036240-6190-11f0-ae4f-dad70ff08860.1980eb50e64 - Recipient: Email of user who created the request
- Content: Simple message "Hello, Your support request has been sent..."
- Attachments: None (confirmation only)
- Merge data: None (static template)
8. RESPONSE AND LOGGINGโ
- Detailed logging of each phase for debugging
- JSON response with complete results of both sends
- Counts: admin emails, attachments, send status
- Error handling with specific messages
Technical Featuresโ
- PROTOCOL: Firebase Cloud Functions v2 with HTTP trigger
- DATABASE: Firestore with 'SupportRequests' and 'Profiles' collections
- EMAIL: ZeptoMail API with custom templates
- STORAGE: Firebase Storage for image downloads
- ATTACHMENTS: Base64 conversion with automatic MIME detection
- TIMEOUT: 30 seconds for image downloads
- FALLBACK: Nodemailer available but not used
- LOGGING: Complete for monitoring and debugging
Error Handlingโ
- Non-POST method โ 405 Method Not Allowed
- Missing ID โ 400 Bad Request
- Support request not found โ 404 Not Found
- No admin found โ 404 Not Found
- ZeptoMail errors โ 500 Internal Server Error
- Image download failed โ Continue without attachment
- User profile not found โ Use email as fallback
Input (Payload):โ
{
"supportRequestId": "tMulEHxpGe4q0Sc9zmaf"
}
Parameters:
supportRequestId(string, required): ID of the document in the 'SupportRequests' collection containing support request details
Output (Success):โ
{
"success": true,
"message": "Email di notifica inviata agli amministratori e email di conferma inviata all'utente",
"adminEmails": ["admin1@arshades.com", "admin2@arshades.com"],
"userEmail": "92mt@live.it",
"attachmentCount": 1,
"adminResponse": { ... },
"userResponse": { ... }
}
Response Properties:
success(boolean): Indicates if the operation was completed successfullymessage(string): Descriptive message of the resultadminEmails(array): List of administrator emails that received the notificationuserEmail(string): Email of the user who received the confirmationattachmentCount(number): Number of attachments processed and sentadminResponse(object): Complete response from admin email sendinguserResponse(object): Complete response from user confirmation email sending
This output is returned in the HTTP response (Postman, browser, curl).
Testingโ
URL (if HTTPS): http://127.0.0.1:5001/arshadesstaging/us-central1/processSupportRequest
Test with Emulator:
- Start the Firebase emulator:
firebase emulators:start --only functions - Ensure you're using Node.js version 20:
nvm use 20 - Test with curl:
curl -X POST "http://127.0.0.1:5001/arshadesstaging/us-central1/processSupportRequest" \
-H "Content-Type: application/json" \
-d '{"supportRequestId": "tMulEHxpGe4q0Sc9zmaf"}'
Postman Testing:
- Method: POST
- URL: http://127.0.0.1:5001/arshadesstaging/us-central1/processSupportRequest
- Headers:
- Key:
Content-Type - Value:
application/json
- Key:
- Body: raw JSON (see examples above)
Deploy Command:โ
firebase deploy --only functions:processSupportRequest
Production URL:โ
processSupportRequest: https://us-central1-arshades-7e18a.cloudfunctions.net/processSupportRequest
Function Name: processSupportRequest
Autore: Domenico Cerone Data di creazione: 25/09/2025
Last Reviewer: Domenico Cerone
Trigger: HTTPS (onRequest)
Purpose: Gestisce l'elaborazione e l'invio di notifiche email per le richieste di supporto degli utenti tramite un sistema di notifica dual. Quando viene ricevuta una richiesta di supporto, invia automaticamente una notifica agli amministratori con tutti i dettagli e gli allegati, e una email di conferma all'utente che ha creato la richiesta.
Funzionamento Dettagliatoโ
Questo modulo gestisce l'elaborazione completa delle richieste di supporto attraverso un sistema di notifica dual:
1. TRIGGER E INPUTโ
- Riceve richieste HTTP POST con parametro 'supportRequestId'
- Esempio:
{ "supportRequestId": "tMulEHxpGe4q0Sc9zmaf" } - Validazione input e controllo metodo HTTP
2. RECUPERO DATI SUPPORT REQUESTโ
- Accede alla collezione Firestore 'SupportRequests'
- Recupera documento usando l'ID fornito come parametro
- Estrae: email, supportType, title, description, createdAt, images[]
- Gestione errore se documento non esiste
3. IDENTIFICAZIONE AMMINISTRATORIโ
- Query sulla collezione 'Profiles' con filtro:
role == 'Admin' - Raccoglie array di email amministratori destinatari
- Fallback error se nessun admin trovato nel sistema
4. RECUPERO PROFILO UTENTE RICHIEDENTEโ
- Usa email dal support request come ID documento in 'Profiles'
- Estrae firstName e lastName per nome completo
- Logica fallback: se nome non disponibile, usa email
- Risultato: "Michele Telesca" oppure "92mt@live.it"
5. CONTROLLO PREFERENZE NOTIFICHEโ
- Controlla se l'utente ha abilitato processSupportRequest nelle sue preferenze di notifica
- Verifica il campo
notification_types.processSupportRequestnel profilo - Se la notifica รจ disabilitata (false): restituisce successo senza inviare email
- Se la notifica รจ abilitata (true): procede con l'identificazione degli amministratori
- Fornisce logging chiaro sullo stato delle preferenze di notifica
6. DOWNLOAD E PREPARAZIONE ALLEGATIโ
- Itera array 'images' dal support request
- Per ogni immagine: download da Firebase Storage URL
- Conversione in formato base64 per allegato email
- Rilevamento automatico MIME type da estensione file
- Timeout 30 secondi per evitare blocchi di rete
- Gestione errori per download falliti
7. INVIO EMAIL DUAL SYSTEMโ
A) EMAIL AMMINISTRATORIโ
- Template:
13ef.8598f19fbcc5adb.k1.d36f1920-618a-11f0-ae4f-dad70ff08860.1980e8f5bb2 - Destinatari: TUTTI gli utenti con role='Admin'
- Allegati: Tutte le immagini del support request
- Dati template:
- profile: nome completo utente ("Michele Telesca")
- createdAt: data formattata italiana ("15/07/2025, 14:51:22")
- supportType: tipo richiesta ("bug_report")
- title: titolo richiesta ("Bug assurdo nella frame!")
- description: descrizione completa problema
B) EMAIL CONFERMA UTENTEโ
- Template:
13ef.8598f19fbcc5adb.k1.94036240-6190-11f0-ae4f-dad70ff08860.1980eb50e64 - Destinatario: Email utente che ha creato la richiesta
- Contenuto: Messaggio semplice "Hello, Your support request has been sent..."
- Allegati: Nessuno (solo conferma)
- Dati template: Nessuna (template statico)
8. RISPOSTA E LOGGINGโ
- Logging dettagliato di ogni fase per debugging
- Risposta JSON con risultati completi di entrambi gli invii
- Conteggi: admin emails, allegati, status invii
- Gestione errori con messaggi specifici
Caratteristiche Tecnicheโ
- PROTOCOLLO: Firebase Cloud Functions v2 con trigger HTTP
- DATABASE: Firestore con collezioni 'SupportRequests' e 'Profiles'
- EMAIL: ZeptoMail API con template personalizzati
- STORAGE: Firebase Storage per download immagini
- ALLEGATI: Conversione base64 con rilevamento MIME automatico
- TIMEOUT: 30 secondi per download immagini
- FALLBACK: Nodemailer disponibile ma non utilizzato
- LOGGING: Completo per monitoring e debugging
Gestione Erroriโ
- Metodo non POST โ 405 Method Not Allowed
- ID mancante โ 400 Bad Request
- Support request non trovato โ 404 Not Found
- Nessun admin trovato โ 404 Not Found
- Errori ZeptoMail โ 500 Internal Server Error
- Download immagini fallito โ Continua senza allegato
- Profilo utente non trovato โ Usa email come fallback
Input (Payload):โ
{
"supportRequestId": "tMulEHxpGe4q0Sc9zmaf"
}
Parametri:
supportRequestId(string, richiesto): ID del documento nella collezione 'SupportRequests' che contiene i dettagli della richiesta di supporto
Output (Success):โ
{
"success": true,
"message": "Email di notifica inviata agli amministratori e email di conferma inviata all'utente",
"adminEmails": ["admin1@arshades.com", "admin2@arshades.com"],
"userEmail": "92mt@live.it",
"attachmentCount": 1,
"adminResponse": { ... },
"userResponse": { ... }
}
Proprietร della Risposta:
success(boolean): Indica se l'operazione รจ stata completata con successomessage(string): Messaggio descrittivo del risultatoadminEmails(array): Lista delle email degli amministratori che hanno ricevuto la notificauserEmail(string): Email dell'utente che ha ricevuto la confermaattachmentCount(number): Numero di allegati elaborati e inviatiadminResponse(object): Risposta completa dall'invio email agli amministratoriuserResponse(object): Risposta completa dall'invio email di conferma all'utente
Questo output viene restituito nella risposta HTTP (Postman, browser, curl).
Testingโ
URL (if HTTPS): http://127.0.0.1:5001/arshadesstaging/us-central1/processSupportRequest
Test con Emulatore:
- Avvia l'emulatore Firebase:
firebase emulators:start --only functions - Assicurati di usare Node.js versione 20:
nvm use 20 - Test con curl:
curl -X POST "http://127.0.0.1:5001/arshadesstaging/us-central1/processSupportRequest" \
-H "Content-Type: application/json" \
-d '{"supportRequestId": "tMulEHxpGe4q0Sc9zmaf"}'
Test con Postman:
- Metodo: POST
- URL: http://127.0.0.1:5001/arshadesstaging/us-central1/processSupportRequest
- Headers:
- Key:
Content-Type - Value:
application/json
- Key:
- Body: raw JSON (vedi esempi sopra)
Deploy Command:โ
firebase deploy --only functions:processSupportRequest
URL di Produzione:โ
processSupportRequest: https://us-central1-arshades-7e18a.cloudfunctions.net/processSupportRequest

